<template>
  <div>
      <div>{{ countDownVal }}</div>
  </div>
</template>

<script>
export default {
  name: 'CountDown',
  props: {
    currentTime: String,
    isDay: Boolean
  },
  data() {
    return {
      countDownVal: ''
    }
  },
  watch: {
    currentTime(val) {
      this.countDown()
    }
  },
  created() {
    this.countDown()
  },
  methods: {
    timeFormat(param) {
      return param < 10 ? '0' + param : param
    },
    countDown() {
      const interval = setInterval(() => {
        // 获取当前时间，同时得到活动结束时间数组
        let newTime = new Date().getTime()
        // 对结束时间进行处理渲染到页面
        let endTime = new Date(this.currentTime).getTime()
        let obj = null
        // 如果活动未结束，对时间进行处理
        if (endTime - newTime > 0) {
          let time = endTime - newTime
          // 获取天、时、分、秒
          let day = parseInt(time / 1000 / 60 / 60 / 24)
          let hours = parseInt(time / 1000 / 60 / 60 % 24)
          let minutes = parseInt(time / 1000 / 60 % 60)
          let seconds = parseInt(time / 1000 % 60)
          obj = {
            day: day,
            hours: this.timeFormat(hours),
            minutes: this.timeFormat(minutes),
            seconds: this.timeFormat(seconds)
          }
          if (this.isDay) {
            this.countDownVal = `抢购剩余时间${obj.day}天${obj.hours}:${obj.minutes}:${obj.seconds}`
          } else {
            this.countDownVal = day > 0 ? `抢购剩余时间${hours + day * 24}:${obj.minutes}:${obj.seconds}` : `抢购剩余时间${obj.hours}:${obj.minutes}:${obj.seconds}`
          }
        } else { // 活动已结束，全部设置为'00'
          obj = {
            day: '00',
            hours: '00',
            minutes: '00',
            seconds: '00'
          }
          clearInterval(interval)
          this.countDownVal = '已结束'
        }
      }, 1000)
    }
  }
}
</script>
